package com.zzyl.nursing.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.IdcardUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.CodeGenerator;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.nursing.domain.*;
import com.zzyl.nursing.dto.CheckInApplyDto;
import com.zzyl.nursing.mapper.*;
import com.zzyl.nursing.service.ICheckInService;
import com.zzyl.nursing.vo.CheckInConfigVo;
import com.zzyl.nursing.vo.CheckInDetailVo;
import com.zzyl.nursing.vo.CheckInElderVo;
import com.zzyl.nursing.vo.ElderFamilyVo;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.List;

/**
 * 入住信息Service业务层处理
 *
 * @author alexis
 * @date 2025-02-25
 */
@Service
public class CheckInServiceImpl extends ServiceImpl<CheckInMapper, CheckIn> implements ICheckInService {
    @Autowired
    private CheckInMapper checkInMapper;
    @Autowired
    private ElderMapper elderMapper;
    @Autowired
    private ElderServiceImpl elderServiceImpl;
    @Autowired
    private ContractMapper contractMapper;
    @Autowired
    private BedMapper bedMapper;
    @Autowired
    private CheckInConfigMapper checkInConfigMapper;

    /**
     * 查询入住信息
     *
     * @param id 入住信息主键
     * @return 入住信息
     */
    @Override
    public CheckIn selectCheckInById(Long id) {
        return checkInMapper.selectById(id);
    }

    /**
     * 查询入住信息列表
     *
     * @param checkIn 入住信息
     * @return 入住信息
     */
    @Override
    public List<CheckIn> selectCheckInList(CheckIn checkIn) {
        return checkInMapper.selectCheckInList(checkIn);
    }

    /**
     * 新增入住信息
     *
     * @param checkIn 入住信息
     * @return 结果
     */
    @Override
    public int insertCheckIn(CheckIn checkIn) {
        return checkInMapper.insert(checkIn);
    }

    /**
     * 修改入住信息
     *
     * @param checkIn 入住信息
     * @return 结果
     */
    @Override
    public int updateCheckIn(CheckIn checkIn) {
        return checkInMapper.updateById(checkIn);
    }

    /**
     * 批量删除入住信息
     *
     * @param ids 需要删除的入住信息主键
     * @return 结果
     */
    @Override
    public int deleteCheckInByIds(Long[] ids) {
        return checkInMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 删除入住信息信息
     *
     * @param id 入住信息主键
     * @return 结果
     */
    @Override
    public int deleteCheckInById(Long id) {
        return checkInMapper.deleteById(id);
    }

    /**
     * 入住详情
     *
     * @param checkInId
     * @return
     */
    @Override
    public CheckInDetailVo detail(Long checkInId) {
        CheckInDetailVo checkInDetailVo = new CheckInDetailVo();
        //获取入住信息
        CheckIn checkIn = checkInMapper.selectById(checkInId);
        //获取入住配置信息
        CheckInConfigVo checkInConfigVo = getCheckInConfigVo(checkInId, checkIn);
        checkInDetailVo.setCheckInConfigVo(checkInConfigVo);

        //获取家属信息
        List<ElderFamilyVo> elderFamilyVoList = JSONUtil.parseArray(checkIn.getRemark()).toList(ElderFamilyVo.class);
        checkInDetailVo.setElderFamilyVoList(elderFamilyVoList);

        //获取老人信息
        Elder elder = elderMapper.selectById(checkIn.getElderId());
        CheckInElderVo checkInElderVo = BeanUtil.toBean(elder, CheckInElderVo.class);

        //计算年龄
        checkInElderVo.setAge(IdcardUtil.getAgeByIdCard(elder.getIdCardNo()));
        checkInDetailVo.setCheckInElderVo(checkInElderVo);

        //获取合同信息
        Contract contract = contractMapper.selectOne(new LambdaQueryWrapper<Contract>().eq(Contract::getElderId, elder.getId()).eq(Contract::getStatus, 1));
        checkInDetailVo.setContract(contract);

        return checkInDetailVo;
    }

    private @NotNull CheckInConfigVo getCheckInConfigVo(Long checkInId, CheckIn checkIn) {
        CheckInConfig checkInConfig = checkInConfigMapper.selectOne(new LambdaQueryWrapper<CheckInConfig>().eq(CheckInConfig::getCheckInId, checkInId));
        CheckInConfigVo checkInConfigVo = new CheckInConfigVo();
        if (ObjectUtil.isNotEmpty(checkInConfig)) {
            checkInConfigVo = BeanUtil.toBean(checkInConfig, CheckInConfigVo.class);
        }
        checkInConfigVo.setStartDate(checkIn.getStartDate());
        checkInConfigVo.setEndDate(checkIn.getEndDate());
        checkInConfigVo.setBedNumber(checkIn.getBedNumber());
        return checkInConfigVo;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int apple(CheckInApplyDto checkInApplyDto) {
        //校验参数
        //校验老人是否已入住
        Elder elder = validateCheckIn(checkInApplyDto.getCheckInElderDto().getIdCardNo());
        //更新床位为已入住
        Bed bed = updateBedStatus(checkInApplyDto.getCheckInConfigDto().getBedId(), 1);
        //新增或更新老人
        elder = saveOrUpdateElder(checkInApplyDto, elder, bed);
        //新增签约办理
        System.out.println(elder);
        insertContract(checkInApplyDto, elder);
        //新增入住信息
        CheckIn checkIn = insertCheckIn(checkInApplyDto, elder, bed);
        //新增入住配置
        insertCheckInConfig(checkInApplyDto, checkIn);
        return 1;
    }

    private Elder saveOrUpdateElder(CheckInApplyDto checkInApplyDto, Elder elder, Bed bed) {
        if (ObjectUtil.isNull(elder)) {
            //新增老人
            elder = BeanUtil.toBean(checkInApplyDto.getCheckInElderDto(), Elder.class);
            elder.setStatus(1);
            elder.setBedNumber(bed.getBedNumber());
            elder.setBedId(checkInApplyDto.getCheckInConfigDto().getBedId());
            elderMapper.insert(elder);
        } else {
            //更新老人
            elder.setImage(checkInApplyDto.getCheckInElderDto().getImage());
            elder.setStatus(1);
            elder.setPhone(checkInApplyDto.getCheckInElderDto().getPhone());
            elder.setAddress(checkInApplyDto.getCheckInElderDto().getAddress());
            elder.setIdCardNationalEmblemImg(checkInApplyDto.getCheckInElderDto().getIdCardNationalEmblemImg());
            elder.setIdCardPortraitImg(checkInApplyDto.getCheckInElderDto().getIdCardPortraitImg());
            elder.setBedNumber(bed.getBedNumber());
            elder.setBedId(bed.getId());
            elderMapper.updateById(elder);
        }
        return elder;
    }

    private void insertCheckInConfig(CheckInApplyDto checkInApplyDto, CheckIn checkIn) {
        CheckInConfig checkInConfig = BeanUtil.toBean(checkInApplyDto.getCheckInConfigDto(), CheckInConfig.class);
        checkInConfig.setCheckInId(checkIn.getId());
        checkInConfig.setSortOrder(0);
        checkInConfigMapper.insert(checkInConfig);
    }

    private CheckIn insertCheckIn(CheckInApplyDto checkInApplyDto, Elder elder, Bed bed) {
        CheckIn checkIn = BeanUtil.toBean(checkInApplyDto.getCheckInConfigDto(), CheckIn.class);
        checkIn.setElderName(elder.getName());
        checkIn.setElderId(elder.getId());
        checkIn.setIdCardNo(elder.getIdCardNo());
        checkIn.setBedNumber(bed.getBedNumber());
        checkIn.setStatus(0);
        checkIn.setSortOrder(0);
        checkIn.setRemark(JSONUtil.toJsonStr(checkInApplyDto.getElderFamilyDtoList()));
        checkInMapper.insert(checkIn);
        return checkIn;
    }

    private void insertContract(CheckInApplyDto checkInApplyDto, Elder elder) {
        Contract contract = BeanUtil.copyProperties(checkInApplyDto.getCheckInContractDto(), Contract.class);
        contract.setElderId(elder.getId());
        contract.setContractNumber(CodeGenerator.generateContractNumber());
        contract.setElderName(elder.getName());
        contract.setStartDate(checkInApplyDto.getCheckInConfigDto().getStartDate());
        contract.setEndDate(checkInApplyDto.getCheckInConfigDto().getEndDate());
        contract.setStatus(1);
        contract.setSortOrder(0);
        contractMapper.insert(contract);
    }

    private Bed updateBedStatus(Long bedId, Integer status) {
        Bed bed = bedMapper.selectById(bedId);
        if (ObjectUtil.isNull(bed)) {
            throw new BaseException("床位不存在");
        }
        bed.setBedStatus(status);
        bed.setUpdateTime(DateUtils.getNowDate());
        bedMapper.updateById(bed);
        return bed;
    }

    private Elder validateCheckIn(String idCardNo) {
        Elder elder = elderMapper.selectOne(new LambdaQueryWrapper<Elder>().eq(Elder::getIdCardNo, idCardNo));
        if (ObjectUtil.isNotNull(elder) && elder.getStatus().equals(1)) {
            //如果老人状态为1,提示已入住
            throw new BaseException("老人已入住");
        }
        return elder;
    }
}
